package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.Track;
import com.xmy.cultivate.service.ITrackService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author min
 * @since 2022-12-27
 */
@RestController
@RequestMapping("/api/track")
public class TrackController {

    @Autowired
    ITrackService iTrackService;

    @GetMapping()
    public Result findAll(@RequestParam Map<String,String> reMap){

        String type = reMap.get("type");
        String classify = reMap.get("classify");
        String yearClassId = reMap.get("yearClassId");

        if (StringUtils.isEmpty(classify)){
            classify = "1";
        }

        String yearPart  = null;
        if (reMap.get("yearPart") != null && !reMap.get("yearPart").isEmpty()) {
            yearPart  = reMap.get("yearPart");
        }
        String quarterNum  = null;
        if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").isEmpty()) {
            quarterNum  = reMap.get("quarterNum");
        }

        QueryWrapper<Track> trackQueryWrapper = new QueryWrapper<>();
        trackQueryWrapper.eq(StringUtils.isNotBlank(type),"type",type);
        trackQueryWrapper.eq("deleted",0);
        trackQueryWrapper.eq("status",1);
        trackQueryWrapper.eq("classify",classify);
        trackQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        trackQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        trackQueryWrapper.orderByAsc("sort");

        StringBuilder yearClassConditions = new StringBuilder();
        if (StringUtils.isNotBlank(yearClassId)) {
            List<String> labelIdList = Arrays.asList(yearClassId.split(","));
            for (String strItem : labelIdList) {
                if (yearClassConditions.length() > 0) {
                    yearClassConditions.append(" OR ");
                }
                yearClassConditions.append("FIND_IN_SET('").append(strItem).append("', label_ids)");
            }
            if (yearClassConditions.length() > 0) {
                trackQueryWrapper.apply(" (" + yearClassConditions.toString() + ") ");
            }
        }

        List<Track> trackList = iTrackService.list(trackQueryWrapper);
        return new Result(Code.OK,new PageResult<>(trackList,(long)trackList.size(),1L));
    }

}
